<template>
	<div class="content">
		<div class="mask_weixincode" v-if="isShowMask" @click="ShowMask()">
			<image :src="userInfo.wxTwoCode" @click.stop="stop">
		</div>
		<div class="content-wrap" v-if="alert == false">
			<div class="content-box">
				<div class="herder">
					<div class="header-left">
						<image :src="userInfo.avatarUrl"></image>
						<div class="information">
							<p class="name">{{userInfo.name}}</p>
							<p class="position">{{userInfo.companyName}}</p>
						</div>
					</div>
					<ul class="contact">
						<li @click="weixin_code">
							<a>
							<image src="../../static/icon_code@2x.png" mode=""></image>
							<p>名片</p>
							</a>
						</li>
						<li>
							<a :href="'tel:'+userInfo.phone">
							<image src="../../static/icon_call@2x.png" mode=""></image>
							<p>电话</p>
							</a>
						</li>
						<li @click="copy_tag()">
							<image src="../../static/icon_wechat@2x.png" mode=""></image>
							<p>微信</p>
						</li>
					</ul>
				</div>
				<div class="title">
					<div class="big-title">{{info.title}}</p></div>
					<div class="small-title"><p>{{info.author}}</p><span>{{info.createTime}}</span></div>

				</div>

				<div v-if="info.type == 3" class="article-detail" v-html="info.details">

				</div>
				<div v-if="info.type == 2" class="article-detail" >

					<div   v-for="(item,index) in info.photosArray" :key="item">
						<image :src="info.photosArray[index]"></image>
					</div>
				</div>
				<input id="hidde" type="text" value="" />
				<div class="goods" v-if="goods && goods.length > 0">
					<div class="goos-title">
						<span></span>
						<p>商品推荐</p>
					</div>
					<div class="goods-list" v-for="item in goods" :key="item">
						<div class="goods-photo">
							<image :src="item.goodsPhoto"></image>
						</div>
						<div class="goods-information">
							<p>{{item.goodsName}}</p>
							<p style="color: #FD634E;font-size: 26upx;">￥{{item.price}}</p>
						</div>
					</div>
				</div>
				<div class="goods" v-if="dynamicDetail && dynamicDetail.length > 0">
					<div class="goos-title">
						<span style='background-color: #FFA133;'></span>
						<p>热文推荐</p>
					</div>
					<div class="goods-list" v-for="item in dynamicDetail" :key="item">
						<div class="goods-photo">
							<image :src="item.photos" mode=""></image>
						</div>
						<div class="goods-information">
							<p>{{item.title}}</p>
							<p style="color: #A8A8A8;font-size: 26upx;">{{item.createTime}}</p>
						</div>
					</div>
				</div>
			</div>

			<div class="bottom">
				<p>以上文章图片部分来源于网络，不代表本平台观点或立场</p>
				<p>若有侵权或者其他违规行为，请联系我们</p>
			</div>
		</div>
		<div class="alert" v-else>
			<image src="../../static/alert.png"></image>
			<p>请在微信端打开该文章</p>
		</div>
	</div>
</template>

<script>
const base64 = require('js-base64').Base64
const jweixin = require('jweixin-module')
	export default {
		data() {
			return {
				//<meta name="referrer" content="never"> 在编译后的index head中加入这个代码
				//替换为自己的域名
				serverUrl:'https://api.youdomain.com/',
				//替换为服务器授权地址
				redirectUri:"http://weixin.youdomain.com/wechatApi/wx/wxAuth",
				//redirectUri:"http://localhost:8080/wechatApi/wx/wxAuth",
				time:0,
				appid:'',
				dynamicId:'',
				userId:'',
				openId:'',
				info:{
					details:"",
					dynamicId:'',
					companyId:'',
					title:'',
					type:'',
					photos:'',
					photosArray:[],
					createTime:''
				},
				alert:false,
				phone:'',
				userInfo:{
					cardId:"",
					companyId:"",
					email:"",
					name:"",
					phone:"",
					personalWx:"",
					wxTwoCode:"",//名片小程序二维码
					userId:"",
					companyName:"",
					avatarUrl:"",
					wxPhone:""
				},
				isShowMask:false,
				createTime:"",
				dynamicDetail:[],
				goods:[],
				jssDk:{
					appId:'',
					timestamp:'',
					nonceStr:'',
					url:'',
					signature:''
 				}
			}
		},

		onShow() {

		},
		onUnload() {
			 
		},
		created(){
			this.createTime = Date.parse(new Date());
		},
		onBackPress(event){
		},

		mounted() {
			
			var ua = navigator.userAgent.toLowerCase();
			var isWeixin = ua.indexOf('micromessenger') != -1;
			if (isWeixin) {
				this.alert = false
				this.wxAuthorize();

			}else{
				this.alert = true
			}
			window.addEventListener('popstate', this.backChange, false)
		},

		methods: {
			pushHistory() {
				var state = {
					title: "title",
					url: "#"    };
				window.history.pushState(state, "title", "#");
			},
			getUrlParam (link) {
			  var url = window.location.href; //获取url中"?"符后的字串
			      var theRequest = new Object();
			      if (url.indexOf("?") != -1) {
			          var str = url.substr(1);
			          var strs = str.split("&");
			          for(var i = 0; i < strs.length; i ++) {
			              theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
			          }
			      }
				  console.log(theRequest)
			      return theRequest;
			},
			getQueryVariable(variable)
			{
			   var query = window.location.search.substring(1);
			   var vars = query.split("&");
			   for (var i=0;i<vars.length;i++) {
					   var pair = vars[i].split("=");
					   if(pair[0] == variable){return pair[1];}
			   }
			   return(false);
			},
			//认证授权
			wxAuthorize() {
				let link = window.location.href;
				console.log(link)
				let params = {};
				//从url获取参数
				params.dynamicId = this.getQueryVariable("dynamicId");
				params.appid = this.getQueryVariable("appid");
				params.userId = this.getQueryVariable("userId");
				//第一次打开存储appid, 如果获取到appid表示第二次进入
				if(!uni.getStorageSync('appid') && params.appid || uni.getStorageSync('dynamicId') != params.dynamicId || !this.getQueryVariable("openId")){
					//清空openID、
				   uni.setStorageSync('openId',"");
				   uni.setStorageSync('appid',params.appid);
				   uni.setStorageSync('dynamicId',params.dynamicId);
				   window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ params.appid+
				   "&redirect_uri="+this.redirectUri+"&response_type=code&scope=snsapi_userinfo&state="+params.appid+"="+params.dynamicId+"#wechat_redirect";
				}else{
					//存放用户访问openid
					if(this.getQueryVariable("openId")) {
						uni.setStorageSync('openId',this.getQueryVariable("openId"));
					}
					if(params.userId && params.dynamicId ){
						var than = this
						if(params.dynamicId){
							var data = {
								dynamicId:params.dynamicId,
								userId:params.userId
							}
							uni.request({
								url: this.serverUrl + 'crmApi/customerEssay/getDynamic',
								method:'POST',
								header: {
								  'content-type': 'application/x-www-form-urlencoded'
								},
								data:{
									data:base64.encode(JSON.stringify(data))
								},
								success(data){
									if(data && data.data && data.data.data && data.data.data.dynamicInfo){
										than.info = data.data.data.dynamicInfo;
										than.info.photosArray = [];
										if(than.info.photos.indexOf(",") != -1){
											const ph = than.info.photos.split(",");
											ph.forEach(item =>{
												than.info.photosArray.push(item);
											})
										}else{
											than.info.photosArray.push(than.info.photos);
										}
										than.info.details = than.formatRichText(than.info.details)
										if(than.info.companyGoodsResponses !== '' && than.info.dynamicDetailResponses !== ''){
											than.goods = than.info.companyGoodsResponses
											for(var i in than.goods){
												than.goods[i].price = (than.goods[i].price/100).toFixed(2)
											}
											than.dynamicDetail = than.info.dynamicDetailResponses
										}
										//计时器开始
										than.timer();
									}
									if(data.data.data.userInfo){
										than.userInfo = data.data.data.userInfo;
									}

									console.log(data)
								},
								fail: function(err) {
								  wx.showToast({
									title: '数据走丢了~',
									duration: 2000,
									icon: 'none'
								  });
								}
							})
						}

						//获取签名
						than.wxJssDKInit(link,params.appid);
					}
				}
			},
			wxJssDKInit(url,appid){
				const than = this;
				var data = {
					appid : appid,
					requestBody : url
				}
				uni.request({
					url:  this.serverUrl +'wechatApi/wx/getWxJsapiSignature',
					method:'POST',
					header: {
					  'content-type': 'application/json'
					},
					data:data ,
					success(result){
						const data = result.data.data;
						if(result.data.code == 200){
							than.weixinJsdk(data,appid);
						}
						console.log(data)
					},
					fail: function(err) {
					  wx.showToast({
						title: '数据走丢了~',
						duration: 2000,
						icon: 'none'
					  });
					}
				})
			},
			/**
			 * 微信jsdk授权
			 * @param {Object} data
			 */
			weixinJsdk(data,appid){
				const than = this;
				jweixin.config({
				  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				  appId: appid, // 必填，公众号的唯一标识
				  timestamp: data.timestamp, // 必填，生成签名的时间戳
				  nonceStr: data.nonceStr, // 必填，生成签名的随机串
				  signature: data.signature,// 必填，签名
				  jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] // 必填，需要使用的JS接口列表
				});
				
				jweixin.ready(function(){
				  // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
				  //分享到朋友圈
				  jweixin.onMenuShareTimeline({
				    title: than.info.title, // 分享标题
				    link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				    imgUrl: than.info.photosArray[0], // 分享图片
				    success: function () {
						// 用户点击了分享后执行的回调函数
						than.addSharNum();
				    }
				  });
				  //分享到朋友
				  jweixin.onMenuShareAppMessage({
				    title: than.info.title, // 分享标题
				    desc: than.userInfo.companyName, // 分享描述
				    link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				    imgUrl: than.info.photosArray[0], // 分享图标
				    type: 'link', // 分享类型,music、video或link，不填默认为link
				    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
				    success: function () {
				      // 用户点击了分享后执行的回调函数
					  than.addSharNum();
				    }
				  });
				
				});
				jweixin.error(function(res){
				  // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
				});
			},
			//添加分享次数
			addSharNum(){
				console.log("添加分享次数:",uni.getStorageSync('dynamicId'));
				let data = {
					dynamicId: uni.getStorageSync('dynamicId')
				}
				uni.request({
					url: this.serverUrl + 'wechatApi/wx/updateShareNum',
					method:'POST',
					header: {
						'content-type': 'application/json'
					},
					data: JSON.stringify(data),
					success(data){
						console.log(data)
					},
					fail: function(err) {
						wx.showToast({
						title: '数据走丢了~',
						duration: 2000,
						icon: 'none'
						});
					}
				})
				
			},
			addStaffData(){
				var openId = uni.getStorageSync('openId');
				if(openId){
					let data = {
						openId:openId ,
						dynamicId: uni.getStorageSync('dynamicId')
					}
					
					uni.request({
						url: this.serverUrl + 'wechatApi/wx/userOpenDynamic',
						method:'POST',
						header: {
							'content-type': 'application/json'
						},
						data: JSON.stringify(data),
						success(data){
							console.log(data)
						},
						fail: function(err) {
							wx.showToast({
							title: '数据走丢了~',
							duration: 2000,
							icon: 'none'
							});
						}
					})
				}
			},
			copy_tag(message){
				var Url2 = this.userInfo.personalWx
				var oInput = document.createElement('input');
				oInput.value = Url2;
				document.body.appendChild(oInput);
				oInput.select(); // 选择对象
				document.execCommand("Copy"); // 执行浏览器复制命令
				oInput.className = 'oInput';
				oInput.style.display='none';
				alert('复制成功');
			},
			weixin_code(){
				this.isShowMask = true
			},
			timer(){
				var than = this
				setInterval(function(){
					than.time++
					than.addStaffData();
				},1000)
			},
			backChange(){
				if(this._gap_time<=5){
					console.log(111)
				  //如果是登录状态，关闭窗口前，移除用户

				}else{
					console.log(2222)
				}
			},
			ShowMask(){
				this.isShowMask = false
			},
			stop(){

				return false
			},
			formatRichText(html){
			  let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
			      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			      return match;
			  });
			  newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
			      match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
			      return match;
			  });
			  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
			  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
			  return newContent;
			},
		},

		destroyed() {

		}
	}
</script>

<style>
body{
	height: 100%;
	width: 100%;
	margin: 0;
	padding:0;
}
.content{
	height: 100%;
	width: 100%;
	box-sizing: border-box;
	font-size: 36upx !important;
	color: #383838;
	position:relative;
}
.content-box{
	width: 100%;
}
.mask_weixincode{
	position: absolute;
	width: 100%;
	height: 100%;
	background-color: rgba(0,0,0,0.5);
	display: flex;
	justify-content: center;
	align-items: center;
}
.mask_weixincode image{
	width: 400upx;
	height: 400upx;
	border-radius: 50%;
}
.content section{
	width: 100% !important;
	font-size: 36upx !important;
}
.photos{
	width: 100%;

}
.photos img{
	width: 100%;
}
.herder{
	height: 160upx;
	display: flex;
	padding-left:30upx;
	padding-right: 30upx;
	align-items: center;
	justify-content: space-between;
	box-shadow: 0 -16upx 30upx #383838;
}
.header-left{
	display: flex;
}
.herder image{
	width: 100upx;
	height: 100upx;
	border-radius:10upx;
}
.information{
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	padding-top:10upx;
	padding-bottom: 7upx;
	margin-left: 22upx;
}
.name{
	font-size: 34upx;
	font-weight: 600;
}
.position{
	font-size: 28upx;
	color: #787878;
}
.contact{
	height: 100upx;
	display: flex;
	width: 240upx;
	justify-content: space-between;
	padding-top: 11upx;
}
.contact image{
	width: 40upx;
	height: 40upx;
	margin-bottom: 20upx;
}
.contact li{
	overflow: hidden;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.contact p{
	font-size: 24upx;
	color: #A8A8A8;
}
.title{
	height: 228upx;
	padding-left:30upx;
	padding-right: 30upx;
	border-bottom: 1upx solid #E8E8E8;
	padding-top: 50upx;
	box-sizing: border-box;
}
.big-title{
	font-size: 36upx;
	font-weight: 600;
	line-height: 1.5;
	color: #383838;
	height: 100upx;
	overflow : hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}
.small-title{
	display: flex;
	font-size: 24upx;
	color: #A8A8A8;
	margin-top: 30upx;
}
.small-title span{
	margin-left: 20upx;
}
.article-detail{
	padding: 30upx;
}
.bottom{
	background: #e3e2e2;
	text-align: center;
	height: 100upx;
	line-height: 1.3;
	padding-top: 30upx;
	width:100%;
	font-size: 24upx;
}
.alert{
	display: flex;
	flex-direction: column;
	align-items: center;
	font-size: 28upx;
	margin-top: 50upx;
}
.alert image{
	width: 100upx;
	height: 100upx;
	margin-bottom: 20upx;
}
.hidde{
	display: hidde;
}
rich-text{
	width: 750upx;
}
.goods{
	width: 690upx;
	box-shadow:0upx 12upx 20upx #E3E2E2;
	border-radius: 20upx;
	margin:0 auto;
	margin-bottom: 30upx;
}
.goos-title{
	height: 88upx;
	display: flex;
	font-size: 32upx;
	font-size: Bold;
	color: #383838;
	align-items: center;
	padding:0 30upx;
	border-bottom:1upx solid #F8F8F8;
}
.goos-title span{
	width: 20upx;
	height: 20upx;
	background-color: #4CD964;
	border-radius: 50%;
	margin-right: 17upx;

}
.goods-list{
	height: 180upx;
	display: flex;
	padding:30upx;
	border-bottom: 1upx solid #F8F8F8;
}
.goods-photo{
	width: 120upx;
	height: 120upx;
	margin-right: 21upx;
}
.goods-photo image{
	width: 100%;
	height: 100%;
	border-radius: 10upx;
}
.goods-information{
	width: 488upx;
	font-size:28upx;
	display: flex;
	flex-direction: column;
	color:rgba(56,56,56,1);
	line-height:38upx;
	justify-content: space-between;
}
.goods-information :first-child{
	width: 100%;
	display: block;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 3;
	overflow: hidden;
	height: 75upx;
}
.article-detail{
	width: 100%;
}
.rich_media_content{
	width: 100%;
}
.rich_media_content section{
	width: 100%;
}
.rich_media_content image{
	max-width: 100%!important;
}

</style>
